﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using HslCommunication.BasicFramework;
using HslCommunication.LogNet;

namespace HslCommunication.Core.Net
{
	/// <summary>
	/// 文件服务器类的基类，为直接映射文件模式和间接映射文件模式提供基础的方法支持，主要包含了对文件的一些操作的功能<br />
	/// The base class of the file server class, which provides basic method support for the direct mapping file mode and the indirect mapping file mode, and mainly includes the functions of some operations on files
	/// </summary>
	// Token: 0x0200013C RID: 316
	public class NetworkFileServerBase : NetworkServerBase
	{
		/// <summary>
		/// 实例化一个默认的对象
		/// </summary>
		// Token: 0x06001B70 RID: 7024 RVA: 0x00088964 File Offset: 0x00086B64
		public NetworkFileServerBase()
		{
			this.dictionaryFilesMarks = new Dictionary<string, FileMarkId>(100);
			this.dictHybirdLock = new object();
		}

		/// <summary>
		/// 获取当前文件的读写锁，如果没有会自动创建，文件名应该是guid文件名，例如 b35a11ec533147ca80c7f7d1713f015b7909<br />
		/// Acquire the read-write lock of the current file. If not, it will be created automatically. 
		/// The file name should be the guid file name, for example, b35a11ec533147ca80c7f7d1713f015b7909
		/// </summary>
		/// <param name="fileName">完整的文件路径</param>
		/// <returns>返回携带文件信息的读写锁</returns>
		// Token: 0x06001B71 RID: 7025 RVA: 0x00088990 File Offset: 0x00086B90
		protected FileMarkId GetFileMarksFromDictionaryWithFileName(string fileName)
		{
			object obj = this.dictHybirdLock;
			FileMarkId fileMarkId;
			lock (obj)
			{
				bool flag2 = this.dictionaryFilesMarks.ContainsKey(fileName);
				if (flag2)
				{
					fileMarkId = this.dictionaryFilesMarks[fileName];
				}
				else
				{
					fileMarkId = new FileMarkId(base.LogNet, fileName);
					this.dictionaryFilesMarks.Add(fileName, fileMarkId);
				}
			}
			return fileMarkId;
		}

		/// <summary>
		/// 接收本次操作的信息头数据
		/// </summary>
		/// <param name="socket">网络套接字</param>
		/// <returns>是否成功的结果对象</returns>
		// Token: 0x06001B72 RID: 7026 RVA: 0x00088A14 File Offset: 0x00086C14
		protected OperateResult<FileGroupInfo> ReceiveInformationHead(Socket socket)
		{
			FileGroupInfo fileGroupInfo = new FileGroupInfo();
			OperateResult<byte[], byte[]> operateResult = base.ReceiveAndCheckBytes(socket, 30000);
			bool flag = !operateResult.IsSuccess;
			OperateResult<FileGroupInfo> result;
			if (flag)
			{
				result = OperateResult.CreateFailedResult<FileGroupInfo>(operateResult);
			}
			else
			{
				fileGroupInfo.Command = BitConverter.ToInt32(operateResult.Content1, 4);
				int num = BitConverter.ToInt32(operateResult.Content1, 0);
				bool flag2 = num == 1001;
				if (flag2)
				{
					fileGroupInfo.FileName = Encoding.Unicode.GetString(operateResult.Content2);
				}
				else
				{
					bool flag3 = num == 1005;
					if (flag3)
					{
						fileGroupInfo.FileNames = HslProtocol.UnPackStringArrayFromByte(operateResult.Content2);
					}
				}
				OperateResult<int, string> operateResult2 = base.ReceiveStringContentFromSocket(socket, 30000);
				bool flag4 = !operateResult2.IsSuccess;
				if (flag4)
				{
					result = OperateResult.CreateFailedResult<FileGroupInfo>(operateResult2);
				}
				else
				{
					fileGroupInfo.Factory = operateResult2.Content2;
					OperateResult<int, string> operateResult3 = base.ReceiveStringContentFromSocket(socket, 30000);
					bool flag5 = !operateResult3.IsSuccess;
					if (flag5)
					{
						result = OperateResult.CreateFailedResult<FileGroupInfo>(operateResult3);
					}
					else
					{
						fileGroupInfo.Group = operateResult3.Content2;
						OperateResult<int, string> operateResult4 = base.ReceiveStringContentFromSocket(socket, 30000);
						bool flag6 = !operateResult4.IsSuccess;
						if (flag6)
						{
							result = OperateResult.CreateFailedResult<FileGroupInfo>(operateResult4);
						}
						else
						{
							fileGroupInfo.Identify = operateResult4.Content2;
							result = OperateResult.CreateSuccessResult<FileGroupInfo>(fileGroupInfo);
						}
					}
				}
			}
			return result;
		}

		/// <summary>
		/// 接收本次操作的信息头数据
		/// </summary>
		/// <param name="socket">网络套接字</param>
		/// <returns>是否成功的结果对象</returns>
		// Token: 0x06001B73 RID: 7027 RVA: 0x00088B68 File Offset: 0x00086D68
		[DebuggerStepThrough]
		protected Task<OperateResult<FileGroupInfo>> ReceiveInformationHeadAsync(Socket socket)
		{
			NetworkFileServerBase.<ReceiveInformationHeadAsync>d__3 <ReceiveInformationHeadAsync>d__ = new NetworkFileServerBase.<ReceiveInformationHeadAsync>d__3();
			<ReceiveInformationHeadAsync>d__.<>t__builder = AsyncTaskMethodBuilder<OperateResult<FileGroupInfo>>.Create();
			<ReceiveInformationHeadAsync>d__.<>4__this = this;
			<ReceiveInformationHeadAsync>d__.socket = socket;
			<ReceiveInformationHeadAsync>d__.<>1__state = -1;
			<ReceiveInformationHeadAsync>d__.<>t__builder.Start<NetworkFileServerBase.<ReceiveInformationHeadAsync>d__3>(ref <ReceiveInformationHeadAsync>d__);
			return <ReceiveInformationHeadAsync>d__.<>t__builder.Task;
		}

		/// <summary>
		/// 获取一个随机的文件名，由GUID码和随机数字组成
		/// </summary>
		/// <returns>文件名</returns>
		// Token: 0x06001B74 RID: 7028 RVA: 0x00088BB4 File Offset: 0x00086DB4
		protected string CreateRandomFileName()
		{
			return SoftBasic.GetUniqueStringByGuidAndRandom();
		}

		/// <summary>
		/// 返回服务器的绝对路径，包含根目录的信息  [Root Dir][Factory][Group][Id] 信息
		/// </summary>
		/// <param name="factory">第一大类</param>
		/// <param name="group">第二大类</param>
		/// <param name="id">第三大类</param>
		/// <returns>是否成功的结果对象</returns>
		// Token: 0x06001B75 RID: 7029 RVA: 0x00088BCC File Offset: 0x00086DCC
		protected string ReturnAbsoluteFilePath(string factory, string group, string id)
		{
			string text = this.m_FilesDirectoryPath;
			bool flag = !string.IsNullOrEmpty(factory);
			if (flag)
			{
				text = text + "\\" + factory;
			}
			bool flag2 = !string.IsNullOrEmpty(group);
			if (flag2)
			{
				text = text + "\\" + group;
			}
			bool flag3 = !string.IsNullOrEmpty(id);
			if (flag3)
			{
				text = text + "\\" + id;
			}
			return text;
		}

		/// <summary>
		/// 返回服务器的绝对路径，包含根目录的信息  [Root Dir][Factory][Group][Id][FileName] 信息
		/// </summary>
		/// <param name="factory">第一大类</param>
		/// <param name="group">第二大类</param>
		/// <param name="id">第三大类</param>
		/// <param name="fileName">文件名</param>
		/// <returns>是否成功的结果对象</returns>
		// Token: 0x06001B76 RID: 7030 RVA: 0x00088C38 File Offset: 0x00086E38
		protected string ReturnAbsoluteFileName(string factory, string group, string id, string fileName)
		{
			return this.ReturnAbsoluteFilePath(factory, group, id) + "\\" + fileName;
		}

		/// <summary>
		/// 返回相对路径的名称
		/// </summary>
		/// <param name="factory">第一大类</param>
		/// <param name="group">第二大类</param>
		/// <param name="id">第三大类</param>
		/// <param name="fileName">文件名</param>
		/// <returns>是否成功的结果对象</returns>
		// Token: 0x06001B77 RID: 7031 RVA: 0x00088C60 File Offset: 0x00086E60
		protected string GetRelativeFileName(string factory, string group, string id, string fileName)
		{
			string str = "";
			bool flag = !string.IsNullOrEmpty(factory);
			if (flag)
			{
				str = str + factory + "\\";
			}
			bool flag2 = !string.IsNullOrEmpty(group);
			if (flag2)
			{
				str = str + group + "\\";
			}
			bool flag3 = !string.IsNullOrEmpty(id);
			if (flag3)
			{
				str = str + id + "\\";
			}
			return str + fileName;
		}

		/// <summary>
		/// 移动一个文件到新的文件去
		/// </summary>
		/// <param name="fileNameOld">旧的文件名称</param>
		/// <param name="fileNameNew">新的文件名称</param>
		/// <returns>是否成功</returns>
		// Token: 0x06001B78 RID: 7032 RVA: 0x00088CD0 File Offset: 0x00086ED0
		protected bool MoveFileToNewFile(string fileNameOld, string fileNameNew)
		{
			bool result;
			try
			{
				FileInfo fileInfo = new FileInfo(fileNameNew);
				bool flag = !Directory.Exists(fileInfo.DirectoryName);
				if (flag)
				{
					Directory.CreateDirectory(fileInfo.DirectoryName);
				}
				bool flag2 = File.Exists(fileNameNew);
				if (flag2)
				{
					File.Delete(fileNameNew);
				}
				File.Move(fileNameOld, fileNameNew);
				result = true;
			}
			catch (Exception ex)
			{
				ILogNet logNet = base.LogNet;
				if (logNet != null)
				{
					logNet.WriteException(this.ToString(), "Move a file to new file failed: ", ex);
				}
				result = false;
			}
			return result;
		}

		/// <summary>
		/// 删除文件并回发确认信息，如果结果异常，则结束通讯
		/// </summary>
		/// <param name="socket">网络套接字</param>
		/// <param name="fullname">完整路径的文件名称</param>
		/// <returns>是否成功的结果对象</returns>
		// Token: 0x06001B79 RID: 7033 RVA: 0x00088D58 File Offset: 0x00086F58
		protected OperateResult DeleteFileAndCheck(Socket socket, string fullname)
		{
			int customer = 0;
			int i = 0;
			while (i < 3)
			{
				i++;
				bool flag = base.DeleteFileByName(fullname);
				if (flag)
				{
					customer = 1;
					break;
				}
				Thread.Sleep(500);
			}
			return base.SendStringAndCheckReceive(socket, customer, StringResources.Language.SuccessText);
		}

		/// <summary>
		/// 文件上传的事件，当文件上传的时候触发。
		/// </summary>
		// Token: 0x1400003D RID: 61
		// (add) Token: 0x06001B7A RID: 7034 RVA: 0x00088DB0 File Offset: 0x00086FB0
		// (remove) Token: 0x06001B7B RID: 7035 RVA: 0x00088DE8 File Offset: 0x00086FE8
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public event NetworkFileServerBase.FileUploadDelegate OnFileUploadEvent;

		/// <summary>
		/// 触发一个文件上传的事件。
		/// </summary>
		/// <param name="fileInfo">文件的基本信息</param>
		// Token: 0x06001B7C RID: 7036 RVA: 0x00088E1D File Offset: 0x0008701D
		protected void OnFileUpload(FileServerInfo fileInfo)
		{
			NetworkFileServerBase.FileUploadDelegate onFileUploadEvent = this.OnFileUploadEvent;
			if (onFileUploadEvent != null)
			{
				onFileUploadEvent(fileInfo);
			}
		}

		/// <summary>
		/// 服务器启动时的操作
		/// </summary>
		// Token: 0x06001B7D RID: 7037 RVA: 0x00088E34 File Offset: 0x00087034
		protected override void StartInitialization()
		{
			bool flag = string.IsNullOrEmpty(this.FilesDirectoryPath);
			if (flag)
			{
				throw new ArgumentNullException("FilesDirectoryPath", "No saved path is specified");
			}
			this.CheckFolderAndCreate();
			base.StartInitialization();
		}

		/// <summary>
		/// 检查文件夹是否存在，不存在就创建
		/// </summary>
		// Token: 0x06001B7E RID: 7038 RVA: 0x00088E70 File Offset: 0x00087070
		protected virtual void CheckFolderAndCreate()
		{
			bool flag = !Directory.Exists(this.FilesDirectoryPath);
			if (flag)
			{
				Directory.CreateDirectory(this.FilesDirectoryPath);
			}
		}

		/// <summary>
		/// 文件所存储的路径
		/// </summary>
		// Token: 0x17000573 RID: 1395
		// (get) Token: 0x06001B7F RID: 7039 RVA: 0x00088E9C File Offset: 0x0008709C
		// (set) Token: 0x06001B80 RID: 7040 RVA: 0x00088EB4 File Offset: 0x000870B4
		public string FilesDirectoryPath
		{
			get
			{
				return this.m_FilesDirectoryPath;
			}
			set
			{
				this.m_FilesDirectoryPath = base.PreprocessFolderName(value);
			}
		}

		/// <summary>
		/// 获取当前的文件标记的对象数量<br />
		/// Get the number of objects marked by the current file
		/// </summary>
		// Token: 0x17000574 RID: 1396
		// (get) Token: 0x06001B81 RID: 7041 RVA: 0x00088EC4 File Offset: 0x000870C4
		public int FileMarkIdCount
		{
			get
			{
				return this.dictionaryFilesMarks.Count;
			}
		}

		/// <inheritdoc cref="F:HslCommunication.Core.Net.NetworkBase.fileCacheSize" />
		// Token: 0x17000575 RID: 1397
		// (get) Token: 0x06001B82 RID: 7042 RVA: 0x0006B82D File Offset: 0x00069A2D
		// (set) Token: 0x06001B83 RID: 7043 RVA: 0x0006B835 File Offset: 0x00069A35
		public int FileCacheSize
		{
			get
			{
				return this.fileCacheSize;
			}
			set
			{
				this.fileCacheSize = value;
			}
		}

		/// <summary>
		/// 获取文件夹的所有文件列表
		/// </summary>
		/// <param name="factory">第一大类</param>
		/// <param name="group">第二大类</param>
		/// <param name="id">第三大类</param>
		/// <returns>文件列表</returns>
		// Token: 0x06001B84 RID: 7044 RVA: 0x00088ED4 File Offset: 0x000870D4
		public virtual string[] GetDirectoryFiles(string factory, string group, string id)
		{
			bool flag = string.IsNullOrEmpty(this.FilesDirectoryPath);
			string[] result;
			if (flag)
			{
				result = new string[0];
			}
			else
			{
				string path = this.ReturnAbsoluteFilePath(factory, group, id);
				bool flag2 = !Directory.Exists(path);
				if (flag2)
				{
					result = new string[0];
				}
				else
				{
					result = Directory.GetFiles(path);
				}
			}
			return result;
		}

		/// <summary>
		/// 获取文件夹的所有文件夹列表
		/// </summary>
		/// <param name="factory">第一大类</param>
		/// <param name="group">第二大类</param>
		/// <param name="id">第三大类</param>
		/// <returns>文件夹列表</returns>
		// Token: 0x06001B85 RID: 7045 RVA: 0x00088F24 File Offset: 0x00087124
		public string[] GetDirectories(string factory, string group, string id)
		{
			bool flag = string.IsNullOrEmpty(this.FilesDirectoryPath);
			string[] result;
			if (flag)
			{
				result = new string[0];
			}
			else
			{
				string path = this.ReturnAbsoluteFilePath(factory, group, id);
				bool flag2 = !Directory.Exists(path);
				if (flag2)
				{
					result = new string[0];
				}
				else
				{
					result = Directory.GetDirectories(path);
				}
			}
			return result;
		}

		/// <inheritdoc />
		// Token: 0x06001B86 RID: 7046 RVA: 0x00088F74 File Offset: 0x00087174
		public override string ToString()
		{
			return "NetworkFileServerBase";
		}

		// Token: 0x04000603 RID: 1539
		private readonly Dictionary<string, FileMarkId> dictionaryFilesMarks;

		// Token: 0x04000604 RID: 1540
		private readonly object dictHybirdLock;

		// Token: 0x04000605 RID: 1541
		private string m_FilesDirectoryPath = null;

		/// <summary>
		/// 文件上传的委托
		/// </summary>
		/// <param name="fileInfo">文件的基本信息</param>
		// Token: 0x0200081C RID: 2076
		// (Invoke) Token: 0x060033D3 RID: 13267
		public delegate void FileUploadDelegate(FileServerInfo fileInfo);
	}
}
